package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@Api(tags = "菜品相关接口")
@RequestMapping("admin/dish")
@RestController
@Slf4j
public class DishController {

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    @ApiOperation("分页查询")
    public Result<PageResult> listDish(DishPageQueryDTO dishPageQueryDTO){
        return Result.success(dishService.listDish(dishPageQueryDTO));
    }

    @GetMapping("/{id}")
    @ApiOperation("由id获取菜品")
    public Result<DishVO> getDishById(@PathVariable Long id){
        return Result.success(dishService.getDishById(id));
    }

    @GetMapping("/list")
    @ApiOperation("由菜品id获取菜品")
    public Result<List<Dish>> getDishByCategoryId(Long categoryId){
        return Result.success(dishService.getDishByCategoryId(categoryId));
    }

    @PostMapping("/status/{status}")
    @ApiOperation("更新菜品状态")
    public Result updateDishStatus(@PathVariable Integer status, Long id){
        log.info("更新菜品状态");
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.updateStates(id, status);
        return Result.success();
    }

    @PostMapping
    @ApiOperation("新增菜品")
    public Result addDish(@RequestBody DishDTO dishDTO){
        String key = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(key);

        log.info(dishDTO.toString());
        dishService.insert(dishDTO);
        return Result.success();
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result updateDish(@RequestBody DishDTO dishDTO){
        log.info(dishDTO.toString());
        Set keys = redisTemplate.keys("dish_*");        //先获取模板
        redisTemplate.delete(keys);
        dishService.update(dishDTO);
        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("批量删除菜品")
    public Result deleteDish(@RequestParam List<Long> ids){
        log.info("批量删除菜品");
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        dishService.delete(ids);
        return Result.success();
    }
}
